import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api'
import { getToken, setToken, clearToken } from '@/utils/request'
import type { User } from '@/types/common'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(getToken())
  const userInfo = ref<User | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value?.nickname || '')
  const userAvatar = computed(() => userInfo.value?.avatarUrl || '')

  // 方法
  
  // 登录
  const login = async (loginData: { username: string; password: string }) => {
    try {
      loading.value = true
      const response = await authApi.login(loginData)
      
      token.value = response.data.token
      userInfo.value = response.data.userInfo as User
      
      setToken(response.data.token)
      localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
      
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerData: any) => {
    try {
      loading.value = true
      const response = await authApi.register(registerData)
      
      token.value = response.data.token
      userInfo.value = response.data.userInfo as User
      
      setToken(response.data.token)
      localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
      
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      if (!token.value) return
      
      const response = await authApi.getUserInfo()
      userInfo.value = response.data
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      return response.data
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能token已过期，清除本地存储
      logout()
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = async (updateData: any) => {
    try {
      loading.value = true
      const response = await authApi.updateUserInfo(updateData)
      userInfo.value = response.data
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      return response
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData: any) => {
    try {
      loading.value = true
      const response = await authApi.changePassword(passwordData)
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 无论请求成功与否，都清除本地存储
      token.value = ''
      userInfo.value = null
      clearToken()
    }
  }

  // 初始化用户信息
  const init = async () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo && token.value) {
      try {
        userInfo.value = JSON.parse(savedUserInfo)
        // 验证token有效性，刷新用户信息
        await fetchUserInfo()
      } catch (error) {
        console.error('初始化用户信息失败:', error)
        logout()
      }
    }
  }

  return {
    // 状态
    token,
    userInfo,
    loading,
    
    // 计算属性
    isLoggedIn,
    userName,
    userAvatar,
    
    // 方法
    login,
    register,
    fetchUserInfo,
    updateUserInfo,
    changePassword,
    logout,
    init
  }
})
